import _ from 'lodash';

export const hasChildren = (list, item) => {
  let result = false;
  list.forEach(value => {
    if (value.pid === item.id) {
      result = true;
    }
  });
  return result;
};

export const findById = (list, id) => {
  let result = null;
  list.forEach(value => {
    if (value.id === id) {
      result = value;
    }
  });
  return result;
};

export const buildSearchPath = (list, pid = '0', pnode = null) => {
  list.forEach(value => {
    const x = value;
    if (`${x.pid}` === pid) {
      let name1 = value.name ? value.name : '';
      const name2 = value.freeTypeName ? value.freeTypeName : '';
      if (value.type === 'org_house_package') {
        name1 = value.areaPart;
      }
      if (value.type === 'org_salingparking') {
        name1 = '可售车位';
      }
      if (value.type === 'org_sale_parking') {
        name1 = '已售车位';
      }
      if (value.type === 'org_not_sale_parking') {
        name1 = '已定价未售车位';
      }
      if (value.type === 'org_forsaleparking') {
        name1 = '未推售车位';
      }
      x.searchPath = pnode && pnode.searchPath ? `${pnode.searchPath}${name1}/` : `/${name1}/`;
      x.searchKeys = [name1, name2];
      x.searchPaths =
        pnode && pnode.searchPaths ? _.concat(pnode.searchPaths, [x.searchPath]) : [x.searchPath];
      if (hasChildren(list, x)) {
        buildSearchPath(list, x.id, x);
      }
    }
  });
};

export const buildTree = (list, pid = '0') => {
  const tree = [];
  list.forEach(value => {
    const x = {
      ...value,
    };
    if (x.pid === pid) {
      if (hasChildren(list, x)) {
        x.children = [];
        x.children = buildTree(list, x.id);
      } else {
        delete x.children;
      }
      tree.push(x);
    }
  });
  return tree;
};

// 构造每行数据方便计算
export const generateRowStructure = (list, params) => {
  const result = [];
  list.forEach(element => {
    // 是楼栋 可编辑均价 可拆分 是否必须拆完
    // 是面积段 可编辑面积、套数 可编辑均价 可删除

    // 是车位父节点 可编辑均价 可拆分  是否必须拆完
    // 是车位叶子节点 可编辑车位数 可编辑均价 可删除
    const rowData = { ...element };

    rowData.errorSplitNum = false;
    rowData.errorSplitSaleArea = false;
    rowData.errorPrice = false;
    rowData.errorNum = false;
    rowData.errorSaleArea = false;
    rowData.errorAreaSegment = false;

    rowData.order = 1;
    rowData.isHouseParent = false;
    rowData.canEditPrice = false;
    rowData.needEditPrice = false;
    rowData.canSplit = false;
    rowData.mustSplit = false;
    rowData.isHouseLeaf = false;
    rowData.canEditOther = false;
    rowData.canRemove = false;
    rowData.isParkingParent = false;
    rowData.isParkingLeaf = false;

    rowData.isParking = _.toNumber(rowData.isParking);
    rowData.isSplit = _.toNumber(rowData.isSplit);
    rowData.averagePrice = _.toNumber(rowData.averagePrice);
    rowData.num = _.toNumber(rowData.num);

    rowData.saleArea = _.toNumber(rowData.saleArea);
    // rowData.isSupply = _.toNumber(rowData.isSupply);
    rowData.averagePrice_house = null;
    rowData.averagePrice_parking = null;
    rowData.num_house = null;
    rowData.num_parking = null;
    rowData.sum_house = null;
    rowData.sum_parking_saling = null;
    rowData.sum_parking_forsale = null;
    rowData.hasCollections = false;

    if (
      rowData.type === 'org_salingparking' ||
      rowData.type === 'org_forsaleparking' ||
      rowData.type === 'org_sale_parking' ||
      rowData.type === 'org_not_sale_parking'
    ) {
      rowData.order = rowData.type === 'org_forsaleparking' ? 999 : 0;
      // 面积段车位 只有我这边拆出来的 org_salingparking 可以编辑 可删除
      rowData.isHouseParent = false;
      rowData.canEditPrice = rowData.type === 'org_salingparking';
      rowData.needEditPrice = rowData.type === 'org_salingparking';
      // 是车位叶子节点 需要变成编辑框
      // rowData.needEditPrice = params.category !== 'strategy';
      rowData.canSplit = false;
      rowData.mustSplit = false;
      rowData.isHouseLeaf = false;
      rowData.canEditOther = rowData.type === 'org_salingparking';
      rowData.canRemove = rowData.type === 'org_salingparking';
      rowData.isParkingParent = false;
      rowData.isParkingLeaf = true;

      rowData.saleArea = null;
      rowData.averagePrice_house = null;
      rowData.averagePrice_parking = rowData.averagePrice;
      rowData.num_house = null;
      rowData.num_parking = rowData.num;
      rowData.sum_house = null;

      const sumParking = _.toNumber(rowData.num_parking) * _.toNumber(rowData.averagePrice_parking);
      if (rowData.type === 'org_forsaleparking') {
        rowData.sum_parking_saling = 0;
        rowData.sum_parking_forsale = sumParking;
      } else {
        rowData.sum_parking_saling = sumParking;
        rowData.sum_parking_forsale = 0;
      }
      const parentNode = _.filter(list, item => item.id === rowData.pid);

      if (
        !(
          !parentNode.businessTypeName ||
          parentNode.businessTypeName === '可售' ||
          parentNode.businessTypeName === '阶段性自持'
        )
      ) {
        rowData.canEditOther = false;
        rowData.canRemove = false;
        rowData.canSplit = false;
        rowData.mustSplit = false;
        rowData.canEditPrice = false;
        rowData.needEditPrice = false;
      }
    }

    if (rowData.type === 'org_house_package' && rowData.isParking !== 1) {
      // 房屋面积段
      rowData.isHouseParent = false;
      rowData.canSplit = false;
      rowData.mustSplit = false;
      rowData.isHouseLeaf = true;
      rowData.isParkingParent = false;
      rowData.isParkingLeaf = false;
      rowData.canEditPrice = false;
      rowData.canEditOther = false;
      rowData.canRemove = false;
      rowData.needEditPrice = params.category !== 'strategy';

      if (rowData.name === '其它') {
        rowData.order = 999;
        if (!params.isMarketing) {
          // 非营销操盘拆出来的（其它）面积段可编辑价格
          rowData.canEditPrice = true;
        } else {
          rowData.canEditPrice = false;
        }
      } else {
        // 归集出来的面积段 不可删  不可编辑
        rowData.canEditPrice = rowData.isSplit !== 1;
        rowData.canEditOther = rowData.isSplit !== 1;
        rowData.canRemove = rowData.isSplit !== 1;
      }

      rowData.averagePrice_house = rowData.averagePrice;
      rowData.averagePrice_parking = null;
      rowData.num_house = rowData.num;
      rowData.num_parking = null;
      rowData.sum_house = rowData.saleArea * rowData.averagePrice_house;
      rowData.sum_parking_saling = null;
      rowData.sum_parking_forsale = null;
    }

    if (rowData.type === 'org_build' && rowData.isParking !== 1) {
      rowData.isHouseParent = true;
      rowData.isParkingParent = false;
      rowData.isParkingLeaf = false;
      rowData.isHouseLeaf = false;
      // 在战规版出现编辑均价输入框
      rowData.needEditPrice = params.category === 'strategy';
      // 有归集  不能编辑
      const items1 = _.filter(
        list,
        item => item.pid === rowData.id && !rowData.isDeleted && rowData.isSplit === 1,
      );
      if (items1.length > 0) {
        rowData.needEditPrice = false;
        rowData.hasCollections = false;
      }

      // 无归集 && 非营销操盘 可编辑
      if (items1.length === 0 && !params.isMarketing) {
        // rowData.needEditPrice = true;
      }
      rowData.canEditPrice = true;
      //  动态判断下面有没有其它   cansplit = child 面积和、车位数和 跟父级的比对  下面一个步骤判断了
      rowData.canSplit = false;
      // 营销操盘必须拆完
      rowData.mustSplit = params.isMarketing;

      rowData.canEditOther = false;
      rowData.canRemove = false;

      // rowData.saleArea = null;
      rowData.averagePrice_house = rowData.averagePrice;
      rowData.averagePrice_parking = null;
      rowData.num_house = rowData.num;
      rowData.num_parking = null;
      rowData.sum_house = null;
      rowData.sum_parking_saling = rowData.saleArea * rowData.averagePrice_house;
      rowData.sum_parking_forsale = 0;
    }

    if (
      rowData.type === (params.category === 'investment' ? 'org_product' : 'org_build') &&
      rowData.isParking === 1
    ) {
      // 车位楼栋
      rowData.isHouseParent = false;
      // 投资版可编辑均价
      rowData.canEditPrice = true;
      rowData.needEditPrice = true;
      // rowData.canEditPrice = params.category === 'investment' || params.category === 'strategy';
      //  动态判断下面有没有其它 下面一个步骤判断了
      rowData.canSplit = false;
      rowData.mustSplit = false;
      rowData.isHouseLeaf = false;
      rowData.canEditOther = false;
      rowData.canRemove = false;
      rowData.isParkingParent = true;
      rowData.isParkingLeaf = false;

      rowData.saleArea = null;
      rowData.averagePrice_house = null;
      rowData.averagePrice_parking = rowData.averagePrice;
      rowData.num_house = null;
      rowData.num_parking = rowData.num;
      rowData.sum_house = null;
      rowData.sum_parking_saling = rowData.num_parking * rowData.averagePrice_parking;
      rowData.sum_parking_forsale = 0;
    }

    if (
      params.category === 'investment' &&
      rowData.type === 'org_product' &&
      rowData.isParking !== 1
    ) {
      // 投资版 业态 编辑均价
      rowData.isHouseParent = false;
      rowData.canEditPrice = true;
      rowData.needEditPrice = true;
      rowData.canSplit = false;
      rowData.mustSplit = false;
      rowData.isHouseLeaf = false;
      rowData.canEditOther = false;
      rowData.canRemove = false;
      rowData.isParkingParent = false;
      rowData.isParkingLeaf = false;

      rowData.averagePrice_house = rowData.averagePrice;
      rowData.averagePrice_parking = null;
      rowData.num_house = rowData.num;
      rowData.num_parking = null;
      rowData.sum_house = rowData.saleArea * rowData.averagePrice_house;
      rowData.sum_parking_saling = 0;
      rowData.sum_parking_forsale = 0;
    }
    if (
      !(
        !rowData.businessTypeName ||
        rowData.businessTypeName === '可售' ||
        rowData.businessTypeName === '阶段性自持'
      )
    ) {
      rowData.canEditOther = false;
      rowData.needEditPrice = false;
      rowData.canRemove = false;
      rowData.canSplit = false;
      rowData.mustSplit = false;
      rowData.canEditPrice = false;
    }

    result.push(rowData);
  });
  return result;
};

// 重新计算 其它 未推售
export const recalculateParentNodes = (list, params) => {
  const all = [];
  list.forEach(element => {
    const node = element;
    if (element.isHouseParent) {
      if (element.id === '29373f8f8f6148d5bd6504ad734c26fb') {
        console.log(params.isMarketing, 'params.isMarketing');
        console.log(element.hasCollections, 'element.hasCollections');
      }
      if (!params.isMarketing) {
        if (!element.hasCollections) {
          node.mustSplit = false;
          node.canSplit = false;
          node.needEditPrice = true;
        }
      }
      // 累计子级 非其它的面积段+套数和
      const children = _.filter(
        list,
        item =>
          item.isHouseLeaf && item.pid === element.id && item.name !== '其它' && !item.isDeleted,
      );
      children.forEach((_item, index) => {
        children[index].needEditPrice = !node.needEditPrice;
      });
      if (children && children.length > 0) {
        const sumData = _.reduce(
          children,
          (sum, item) => {
            const saleAreaSum = sum.saleArea + (item.saleArea ? item.saleArea : 0);
            const numHouse = sum.num_house + (item.num_house ? item.num_house : 0);
            return {
              num_house: numHouse,
              saleArea: saleAreaSum,
            };
          },
          {
            num_house: 0,
            saleArea: 0,
          },
        );
        // 比较差值 判断是否需要其它
        if (element.num_house !== sumData.num_house || element.saleArea !== sumData.saleArea) {
          node.canSplit = true;
          const fookOthers = _.filter(
            list,
            item =>
              item.isHouseLeaf &&
              item.pid === element.id &&
              item.name === '其它' &&
              item.isDeleted !== true,
          );

          const numHouse = node.num_house - sumData.num_house;
          const saleArea = node.saleArea - sumData.saleArea;
          // const fookOtherAveragePrice = element.averagePrice;

          if (fookOthers && fookOthers.length > 0) {
            const fookOther = fookOthers[0];
            fookOther.xmm = '延续旧的';
            fookOther.needEditPrice = !node.needEditPrice;
            fookOther.num_house = numHouse > 0 ? numHouse : 0;
            fookOther.saleArea = saleArea > 0 ? saleArea : 0;
            fookOther.sum_house = fookOther.saleArea * fookOther.averagePrice_house;
          } else {
            // 增加其它
            const rowData = {};
            rowData.xmm = '新增的';
            rowData.type = 'org_house_package';
            rowData.isHouseParent = false;
            rowData.canSplit = false;
            rowData.mustSplit = false;
            rowData.isHouseLeaf = true;
            rowData.isParkingParent = false;
            rowData.isParkingLeaf = false;
            rowData.canEditPrice = false;
            rowData.canEditOther = false;
            rowData.canRemove = false;
            rowData.isNew = true;
            rowData.name = '其它';
            rowData.areaPart = '其它';
            rowData.needEditPrice = !node.needEditPrice;
            if (!params.isMarketing) {
              // 非营销操盘拆出来的（其它）面积段可编辑价格
              rowData.canEditPrice = true;
            } else {
              rowData.canEditPrice = false;
            }

            rowData.averagePrice = 0;
            rowData.averagePrice_house = 0;
            rowData.averagePrice_parking = null;
            rowData.num_house = numHouse > 0 ? numHouse : 0;
            rowData.saleArea = saleArea > 0 ? saleArea : 0;
            rowData.num_parking = null;
            rowData.sum_house = 0;
            rowData.sum_parking_saling = null;
            rowData.sum_parking_forsale = null;
            rowData.pid = node.id;
            rowData.id = `${+new Date()}${node.id}`;
            all.push(rowData);
          }
        } else {
          const fookOthers = _.filter(
            list,
            item =>
              item.isHouseLeaf &&
              item.pid === element.id &&
              item.name === '其它' &&
              !item.isDeleted,
          );
          if (fookOthers && fookOthers.length > 0) {
            fookOthers.forEach((_item, i) => {
              fookOthers[i].isDeleted = true;
            });
          }
          if (element.num_house !== 0 || element.saleArea !== 0) {
            // 没有子集 and 没拆完 canSplit=true
            node.canSplit = true;
          }
        }
      } else {
        // 删除其它
        const fookOthers = _.filter(
          list,
          item =>
            item.isHouseLeaf && item.pid === element.id && item.name === '其它' && !item.isDeleted,
        );
        if (fookOthers && fookOthers.length > 0) {
          fookOthers.forEach((_item, i) => {
            fookOthers[i].isDeleted = true;
          });
        }
        if (element.num_house !== 0 || element.saleArea !== 0) {
          // 没有子集 and 没拆完 canSplit=true
          node.canSplit = true;
        }
      }
      if (!params.isMarketing) {
        if (!element.hasCollections) {
          node.mustSplit = false;
          node.canSplit = false;
          node.needEditPrice = true;
        }
      }
      // 其它算出来之后  重新计算楼栋均价
      const childrenx = _.filter(
        list,
        item =>
          item.isHouseLeaf &&
          item.pid === element.id &&
          item.averagePrice_house > 0 &&
          !item.isDeleted,
      );
      if (childrenx && childrenx.length > 0) {
        const sumData = _.reduce(
          childrenx,
          (sum, item) => {
            const saleAreaSum = sum.saleArea + (item.saleArea ? item.saleArea : 0);
            const sumHouse = sum.sum_house + (item.sum_house ? item.sum_house : 0);
            return {
              sum_house: sumHouse,
              saleArea: saleAreaSum,
            };
          },
          {
            sum_house: 0,
            saleArea: 0,
          },
        );
        const averagePrice = sumData.saleArea > 0 ? sumData.sum_house / sumData.saleArea : 0;
        if (averagePrice > 0) {
          node.averagePrice = averagePrice;
          node.averagePrice_house = averagePrice;
        }
      }
    }
    if (element.isParkingParent) {
      // 累计子级 非其它的车位数
      const children = _.filter(
        list,
        item =>
          item.isParkingLeaf &&
          item.pid === element.id &&
          item.type !== 'org_forsaleparking' &&
          !item.isDeleted,
      );
      if (children && children.length > 0) {
        const sumData = _.reduce(
          children,
          (sum, item) => {
            const numParking = sum.num_parking + (item.num_parking ? item.num_parking : 0);
            const sumParkingSaling =
              sum.sum_parking_saling + (item.sum_parking_saling ? item.sum_parking_saling : 0);
            return {
              num_parking: numParking,
              sum_parking_saling: sumParkingSaling,
            };
          },
          {
            num_parking: 0,
            sum_parking_saling: 0,
          },
        );
        const averagePrice =
          sumData.num_parking > 0 ? sumData.sum_parking_saling / sumData.num_parking : 0;

        if (averagePrice > 0) {
          node.averagePrice = averagePrice;
          node.averagePrice_parking = averagePrice;
        }
        node.needEditPrice = false;
        const fookOthers = _.filter(
          list,
          item =>
            item.isParkingLeaf &&
            item.pid === element.id &&
            item.type === 'org_forsaleparking' &&
            !item.isDeleted,
        );
        // 比较差值 判断是否需要其它
        if (element.num_parking !== sumData.num_parking) {
          node.canSplit = true;
          const numParking = node.num_parking - sumData.num_parking;
          if (node.id === '66803b9e0ed348a5aa7358483797010e') {
            window.console.log(numParking, 'numParking');
            window.console.log(node, 'node');
            window.console.log(sumData.num_parking, 'sumData.num_parking');
          }
          if (fookOthers && fookOthers.length > 0) {
            const fookOther = fookOthers[0];
            fookOther.averagePrice = element.averagePrice;
            fookOther.averagePrice_parking = element.averagePrice;
            fookOther.num = numParking > 0 ? numParking : 0;
            fookOther.num_parking = numParking > 0 ? numParking : 0;
            fookOther.sum_parking_forsale = fookOther.num_parking * fookOther.averagePrice_parking;

            // 父节点剩余多少未拆分完 校验用
          } else {
            // 增加其它
            const rowData = {};
            rowData.type = 'org_forsaleparking';
            rowData.isHouseParent = false;
            rowData.canSplit = false;
            rowData.mustSplit = false;
            rowData.isHouseLeaf = false;
            rowData.isParkingParent = false;
            rowData.isParkingLeaf = true;
            rowData.canEditPrice = false;
            rowData.canEditOther = false;
            rowData.canRemove = false;
            rowData.isNew = true;
            rowData.name = '未推售车位';

            rowData.averagePrice = node.averagePrice;
            rowData.averagePrice_parking = node.averagePrice;
            rowData.averagePrice_house = null;
            rowData.num = numParking > 0 ? numParking : 0;
            rowData.num_parking = numParking > 0 ? numParking : 0;
            rowData.sum_house = null;
            rowData.sum_parking_saling = null;
            rowData.sum_parking_forsale = rowData.num_parking * rowData.averagePrice_parking;
            rowData.pid = node.id;
            rowData.id = `${+new Date()}${node.id}`;
            all.push(rowData);
          }
        } else if (fookOthers && fookOthers.length > 0) {
          const fookOther = fookOthers[0];
          fookOther.isDeleted = true;
          fookOther.averagePrice = element.averagePrice;
          fookOther.averagePrice_parking = element.averagePrice;
          fookOther.num = 0;
          fookOther.num_parking = 0;
          fookOther.sum_parking_forsale = 0;
          // 父节点剩余多少未拆分完 校验用
        }
      } else {
        node.needEditPrice = true;
        const fookOthers = _.filter(
          list,
          item =>
            item.isParkingLeaf &&
            item.pid === element.id &&
            item.type === 'org_forsaleparking' &&
            !item.isDeleted,
        );
        if (fookOthers && fookOthers.length > 0) {
          fookOthers.forEach((_item, i) => {
            fookOthers[i].isDeleted = true;
          });
        }
        if (element.num_parking > 0) {
          node.canSplit = true;
        }
      }
    }

    if (
      !(
        !element.businessTypeName ||
        element.businessTypeName === '可售' ||
        element.businessTypeName === '阶段性自持'
      )
    ) {
      node.canEditOther = false;
      node.canRemove = false;
      node.canSplit = false;
      node.mustSplit = false;
      node.canEditPrice = false;
      node.needEditPrice = false;
    }
    all.push(node);
  });
  return all;
};

export const calculateValidateOptions = (list, params) => {
  list.forEach(element => {
    const node = element;
    if (params.category === 'investment' && node.type === 'org_product' && node.isParking !== 1) {
      if (node.canEditPrice && node.averagePrice_house <= 0) {
        node.errorPrice = true;
      }
    }

    if (element.isHouseParent) {
      if (element.canEditPrice && element.averagePrice_house <= 0) {
        node.errorPrice = true;
      }
      // 父节点剩余多少未拆分完 校验用
      const childrenOrthers = _.filter(
        list,
        item => item.pid === node.id && item.name === '其它' && !item.isDeleted,
      );
      const childrenxx = _.filter(
        list,
        item => item.isHouseLeaf && item.pid === node.id && item.name !== '其它' && !item.isDeleted,
      );

      if (childrenOrthers && childrenOrthers.length > 0) {
        const childrenOrther = childrenOrthers[0];
        node.left_num_house = childrenOrther.num_house;
        node.left_saleArea = childrenOrther.saleArea;
      } else if (childrenxx && childrenxx.length > 0) {
        node.left_num_house = 0;
        node.left_saleArea = 0;
      } else {
        node.left_num_house = node.num_house;
        node.left_saleArea = node.saleArea;
      }
      if (node.mustSplit) {
        if (node.left_num_house !== 0) {
          node.errorSplitNum = true;
        }
        if (node.left_saleArea !== 0) {
          node.errorSplitSaleArea = true;
        }
      }

      if (childrenxx && childrenxx.length > 0) {
        childrenxx.forEach((child, index) => {
          if (child.canEditPrice && child.averagePrice_house <= 0) {
            childrenxx[index].errorPrice = true;
          }
          if (child.canEditOther && child.saleArea <= 0) {
            childrenxx[index].errorSaleArea = true;
          }
          // if (child.canEditOther && child.num_house <= 0) {
          //   childrenxx[index].errorNum = true;
          // }
          if (
            child.canEditOther &&
            (!!child.areaPart === false || child.areaPart === '请选择面积段')
          ) {
            childrenxx[index].errorAreaSegment = true;
          }
          childrenxx[index].left_num_house = node.left_num_house;
          childrenxx[index].left_saleArea = node.left_saleArea;
        });
      }
    }
    if (element.isParkingParent) {
      // 父节点剩余多少未拆分完 校验用
      const childrenOrthers = _.filter(
        list,
        item =>
          item.isParkingLeaf &&
          item.pid === element.id &&
          item.type === 'org_forsaleparking' &&
          !item.isDeleted,
      );
      const childrenxx = _.filter(
        list,
        item =>
          item.isParkingLeaf &&
          item.pid === element.id &&
          item.type !== 'org_forsaleparking' &&
          !item.isDeleted,
      );

      if (childrenOrthers && childrenOrthers.length > 0) {
        const childrenOrther = childrenOrthers[0];
        node.left_num_parking = childrenOrther.num_parking;
      } else if (childrenxx && childrenxx.length > 0) {
        node.left_num_parking = 0;
      } else {
        node.left_num_parking = node.num_parking;
      }
      if (node.canEditPrice && node.averagePrice_parking <= 0) {
        node.errorPrice = true;
      }

      if (childrenxx && childrenxx.length > 0) {
        childrenxx.forEach((child, index) => {
          if (child.canEditPrice && child.averagePrice_parking <= 0) {
            childrenxx[index].errorPrice = true;
          }
          if (child.canEditOther && child.num_parking <= 0) {
            childrenxx[index].errorNum = true;
          }
          childrenxx[index].left_num_parking = node.left_num_parking;
        });
      }
    }
  });
  return list;
};
export const canSave = list => {
  for (let i = 0; i < list.length; i += 1) {
    const rowData = list[i];
    if (
      rowData.errorSplitNum ||
      rowData.errorSplitSaleArea ||
      rowData.errorPrice ||
      rowData.errorNum ||
      rowData.errorSaleArea ||
      rowData.errorAreaSegment
    ) {
      return false;
    }
  }
  return true;
};

const calculateRowData = (data, params) => {
  let rowData = data;
  if (
    !(
      !rowData.businessTypeName ||
      rowData.businessTypeName === '可售' ||
      rowData.businessTypeName === '阶段性自持'
    )
  ) {
    return data;
  }
  if (
    rowData.isParkingLeaf ||
    rowData.isParkingParent ||
    rowData.isHouseLeaf ||
    rowData.isHouseParent
  ) {
    rowData.sum_house = null;
    rowData.sum_parking_saling = null;
    rowData.sum_parking_forsale = null;
    if (rowData.isParkingLeaf) {
      if (rowData.type === 'org_forsaleparking') {
        rowData.sum_parking_forsale = rowData.averagePrice_parking * rowData.num_parking;
      } else {
        rowData.sum_parking_saling = rowData.averagePrice_parking * rowData.num_parking;
      }
    }
    if (rowData.isHouseLeaf) {
      rowData.sum_house = rowData.averagePrice_house * rowData.saleArea;
    }
    if (rowData.isParkingParent || rowData.isHouseParent) {
      if (rowData.children && rowData.children.length > 0) {
        rowData.sum_house = null;
        rowData.sum_parking_saling = null;
        rowData.sum_parking_forsale = null;
        const sumData = _.reduce(
          rowData.children,
          (sum, item) => {
            const sumHouse = sum.sum_house + (item.sum_house ? item.sum_house : 0);
            const sumParkingSaling =
              sum.sum_parking_saling + (item.sum_parking_saling ? item.sum_parking_saling : 0);
            const sumParkingForsale =
              sum.sum_parking_forsale + (item.sum_parking_forsale ? item.sum_parking_forsale : 0);
            return {
              sum_house: sumHouse,
              sum_parking_saling: sumParkingSaling,
              sum_parking_forsale: sumParkingForsale,
            };
          },
          {
            sum_house: 0,
            sum_parking_saling: 0,
            sum_parking_forsale: 0,
          },
        );
        rowData.sum_house = sumData.sum_house;
        rowData.sum_parking_saling = sumData.sum_parking_saling;
        rowData.sum_parking_forsale = sumData.sum_parking_forsale;
      } else {
        rowData.sum_parking_forsale = 0;
        rowData.sum_parking_saling = 0;
        rowData.sum_house = 0;
        if (rowData.isParkingParent) {
          rowData.sum_parking_saling = rowData.num_parking * rowData.averagePrice;
        }
        if (rowData.isHouseParent) {
          rowData.sum_house = rowData.saleArea * rowData.averagePrice;
        }
      }
    }
  } else {
    const sumData = _.reduce(
      rowData.children,
      (sum, item) => {
        if (
          !(
            !item.businessTypeName ||
            item.businessTypeName === '可售' ||
            item.businessTypeName === '阶段性自持'
          )
        ) {
          return sum;
        }
        const sumHouse = sum.sum_house + (item.sum_house ? item.sum_house : 0);
        const sumParkingSaling =
          sum.sum_parking_saling + (item.sum_parking_saling ? item.sum_parking_saling : 0);
        const sumParkingForsale =
          sum.sum_parking_forsale + (item.sum_parking_forsale ? item.sum_parking_forsale : 0);
        const saleAreaSum = sum.saleArea + (item.saleArea ? item.saleArea : 0);
        const numHouse = sum.num_house + (item.num_house ? item.num_house : 0);
        const numParking = sum.num_parking + (item.num_parking ? item.num_parking : 0);

        const averagePriceHouse = saleAreaSum === 0 ? 0 : sumHouse / saleAreaSum;
        const averagePriceParking =
          numParking === 0 ? 0 : (sumParkingSaling + sumParkingForsale) / numParking;

        return {
          averagePrice_house: averagePriceHouse,
          averagePrice_parking: averagePriceParking,
          num_house: numHouse,
          saleArea: saleAreaSum,
          num_parking: numParking,
          sum_house: sumHouse,
          sum_parking_saling: sumParkingSaling,
          sum_parking_forsale: sumParkingForsale,
        };
      },
      {
        averagePrice_house: 0,
        averagePrice_parking: 0,
        num_parking: 0,
        num_house: 0,
        saleArea: 0,
        sum_house: 0,
        sum_parking_saling: 0,
        sum_parking_forsale: 0,
      },
    );
    if (
      params &&
      params.category === 'investment' &&
      rowData.type === 'org_product' &&
      rowData.isParking !== 1
    ) {
      rowData = {
        ...rowData,
        sum_house: rowData.averagePrice_house * rowData.saleArea,
        sum_parking_saling: null,
        sum_parking_forsale: null,
      };
    } else {
      rowData = {
        ...rowData,
        ...sumData,
      };
    }
  }

  return rowData;
};
const traverseCalculate = (items, params) => {
  const x = items.map(element => {
    let y = element;
    if (element.children && element.children.length > 0) {
      y.children = traverseCalculate(element.children, params);
    }
    y = calculateRowData(y, params);
    return y;
  });
  return x;
};
export const calculateTreeData = (treeData, params) => traverseCalculate(treeData, params);

export const getSearchItems = list => {
  const items = {};
  let types = [];
  // 筛选出所有类型
  _(list).forEach(value => {
    types.push(value.type);
  });
  // 去重
  types = _.uniq(types);
  // 类型数组
  _(types).forEach(value => {
    items[value] = [];
  });
  // 遍历相同类型的对象插入数组
  _(list).forEach(value => {
    _(types).forEach(val => {
      if (val === value.type) {
        items[val].push(value);
      }
    });
  });

  return items;
};

export const getSearchTypeItems = (list, name, code) => {
  const data = [];
  _(list).forEach(value => {
    if (value[`${name}`] && value[`${code}`]) {
      data.push({
        name: value[`${name}`],
        code: value[`${name}`],
      });
    }
  });
  return _.uniqBy(data, 'name');
};

export const getSearchLists = list => {
  const data = [];
  _(list).forEach(value => {
    data.push({
      name: value.name,
      code: value.id,
    });
  });
  return _.uniqBy(data, 'name');
};

// 显示的select下拉框
export const getSelects = tabKey => {
  let formItems = [];
  if (tabKey !== 'investment') {
    formItems = [
      {
        id: 'trade',
        label: '业态',
        span: 6,
      },
      {
        id: 'build',
        label: '楼栋',
        span: 6,
      },
      {
        id: 'tradeAttr',
        label: '产品属性',
        span: 6,
      },
      {
        id: 'area',
        label: '面积段',
        span: 6,
      },
    ];
  } else {
    formItems = [
      {
        id: 'productConstitute',
        label: '产品构成',
        span: 6,
      },
      {
        id: 'supplyBatch',
        label: '供应批次',
        span: 6,
      },
      {
        id: 'decorationStandard',
        label: '装修标准',
        span: 6,
      },
      // {
      //   id: 'attributeTag',
      //   label: '属性标签',
      //   span: 6,
      // },
    ];
  }
  return formItems;
};

export const getExpandedRowKeys = list => {
  const expandedRowKeys = [];
  _.forEach(list, value => {
    expandedRowKeys.push(value.id);
  });
  return expandedRowKeys;
};

export const filterAll = ({ all, query }) => {
  const leafNodes = _.filter(all, item => {
    let result = null;
    if (query.trade && item.type === 'org_product') {
      if (item.proProductName === query.trade && item.type === 'org_product') {
        result = true;
      } else {
        return false;
      }
    }
    if (query.decorationStandard) {
      if (item.freeTypeName === query.decorationStandard && item.type === 'org_product') {
        result = true;
      } else {
        return false;
      }
    }
    if (query.supplyBatch) {
      if (item.searchPath.search(`/${query.supplyBatch}/`) > -1) {
        result = true;
      } else {
        return false;
      }
    }
    if (query.productConstitute) {
      if (item.searchPath.search(`/${query.productConstitute}/`) > -1) {
        result = true;
      } else {
        return false;
      }
    }
    if (query.area) {
      if (item.searchPath.search(`/${query.area}/`) > -1) {
        result = true;
      } else {
        return false;
      }
    }
    if (query.tradeAttr) {
      if (item.searchPath.search(`/${query.tradeAttr}/`) > -1) {
        result = true;
      } else {
        return false;
      }
    }
    if (query.build) {
      if (item.searchPath.search(`/${query.build}/`) > -1) {
        result = true;
      } else {
        return false;
      }
    }
    return result;
  });

  let searchPaths = [];
  if (leafNodes && leafNodes.length > 0) {
    leafNodes.forEach(item => {
      searchPaths = _.union(searchPaths, item.searchPaths);
    });
  }
  // console.log(query, 'query');
  // console.log(leafNodes, 'leafNodes');
  // console.log(searchPaths, 'searchPaths');
  return _.filter(all, item => _.findIndex(searchPaths, item2 => item2 === item.searchPath) > -1);
};

export const tree2array = tree => {
  const items = [];
  tree.forEach(element => {
    items.push({
      ...element,
      children: null,
    });
    if (element.children && element.children.length > 0) {
      const childrens = tree2array(element.children);
      if (childrens && childrens.length > 0) {
        items.push(...childrens);
      }
    }
  });
  return items;
};

export const getItemsForSave = (tree, all) => {
  // 校验
  // 把tree平铺
  // TODO 合并面积段相同的

  const list = tree2array(tree);
  const deletedItems = _.filter(all, item => item.isDeleted);

  console.log(deletedItems, 'deletedItems');
  console.log(all, 'all');

  list.push(...deletedItems);
  const items = {};
  let types = [];
  // 筛选出所有类型
  _(list).forEach(value => {
    types.push(value.type);
  });
  // 去重
  types = _.uniq(types);
  // 类型数组
  _(types).forEach(value => {
    items[value] = [];
  });
  // 遍历相同类型的对象插入数组
  _(list).forEach((value, index) => {
    _(types).forEach(val => {
      if (val === value.type) {
        if (
          value.type === 'org_salingparking' ||
          value.type === 'org_forsaleparking' ||
          value.type === 'org_sale_parking' ||
          value.type === 'org_not_sale_parking'
        ) {
          list[index].averagePrice = value.averagePrice_parking;
          list[index].num = value.num_parking;
        }
        if (value.type === 'org_house_package') {
          const parentNodes = _.filter(list, item => item.id === value.pid);
          if (parentNodes && parentNodes.length > 0) {
            const parentNode = parentNodes[0];
            if (value.name !== '其它') {
              list[index].isSplit = parentNode.isSplit ? 1 : 0;
            }
          }
          list[index].averagePrice = value.averagePrice_house;
          list[index].num = value.num_house;
        }
        items[val].push(value);
      }
    });
  });
  //   房源包 org_house_package
  // 可售车位 org_salingparking
  // 已售车位 org_sale_parking
  // 已定价未售车位 org_not_sale_parking
  items.org_house = [];

  if (items.org_house_package) {
    items.org_house.push(...items.org_house_package);
  }
  if (items.org_forsaleparking) {
    items.org_house.push(...items.org_forsaleparking);
  }
  if (items.org_salingparking) {
    items.org_house.push(...items.org_salingparking);
  }
  if (items.org_sale_parking) {
    items.org_house.push(...items.org_sale_parking);
  }
  if (items.org_not_sale_parking) {
    items.org_house.push(...items.org_not_sale_parking);
  }
  return items;
};

// 删除其它
// 保存all
// 过滤删除的数据
// 构造每行数据方便计算
//  先构造父级 会追加出其它+未推售子节点 不计算出父级的均价（）
//  构造leaf节点
// 生成树 计算
//  除了叶子节点的均价 其它均价 套数 面积 车位数 都应该是累积重新计算的

// 编辑时
//  重新计算本行
//  重新构造父级 追加出其它+未推售子节点
//  重新生成树 计算
// 保存
//  把tree变成数组 加上delete的node 一并提交

// 搜索 构成树
//  重新生成树 计算 （搜索面积段的时候 要去掉车位相关节点）
// window.console.log(all, 'generateRowStructure');

// 构造tree
// 重新计算tree的值（面积段、可售车位等 不用重新计算均价   分两个层次 一个是叶子节点（面积段） 一个是以上）

export const getCalculatedTree = (all, params) => {
  let list = _.cloneDeep(_.filter(all, item => item.isDeleted !== true));
  list = _.orderBy(list, ['order'], ['asc']);

  const tree = buildTree(list, '0');
  // window.console.log(tree, 'tree');
  return calculateTreeData(tree, params);
};
